<?php

namespace App\Http\Controllers\Manage;

use App\Helpers\ResponseData;
use App\Helpers\Untils;
use App\Http\Controllers\Controller;
use App\Imports\ShortCut;
use App\Models\CustomerManager;
use App\Models\CustomerManagerShop;
use App\Models\ShopManageDetail;
use App\Models\ShopManager;
use App\Models\ShopManageRecord;
use App\Models\ShortCutRecord;
use App\Models\SystemUser;
use App\Notifications\InvoicePaid;
use App\Notifications\ShopManage;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Maatwebsite\Excel\Facades\Excel;
//已废弃
class ShopManageController extends Controller
{
    use ResponseData,Untils;
    public function list(ShopManager $model,Request $request){
        $size = $request->input('size',10);
        $model = $model->with('platForm','customer','template','department','detail');
        if($request->filled('shop_name')){
            $model = $model->where('shop_name','like','%'.$request->shop_name.'%');
        }
        if($request->filled('customer_name')){
            $customer = $customer = CustomerManager::query()->where('company_name','like','%'.$request->customer_name.'%')->pluck('id');
            if(count($customer)>0){
                $model = $model->whereIn('customer_id',$customer);
            }
        }
        if($request->filled('customer_id')){
            $model = $model->where('customer_id',$request->customer_id);
        }
        if($request->filled('start')&&$request->filled('end')){
            $model = $model->whereBetween('created_at',[$request->start,$request->end]);
        }
//        if($request->filled('status')&&$request->status=='all'){
//            $data = $model->orderBy('id','desc')->get();
//        }else{
        $data = $model->orderBy('id','desc')->paginate($size);

//        }
        return $this->success($data);
    }

    public function store(ShopManager $model,Request $request){
        $data = $request->only('customer_id','wx_group','distance_price','plateform_id','template_id','department_id','shop_name','template_name','group_id','store_category');
        DB::transaction(function ()use($data,$request) {
            $data['created_at'] = now();
            $data['updated_at'] = now();
            $id = DB::table('shop_managers')->insertGetId($data);
            if($id){
                $arr = $this->getData($request);
                if(is_array($arr)){
                    foreach ($arr as $k=>$v){
                        $map[$k]['shop_manage_id'] = $id;
                        $map[$k]['model_id'] = isset($v['model_id'])?$v['model_id']:0;
                        $map[$k]['key'] = isset($v['key'])?$v['key']:'';
                        $map[$k]['value'] = isset($v['value'])?json_encode($v['value']):'';
                        $map[$k]['mark'] = isset($v['mark'])?$v['mark']:'';
                        $map[$k]['other'] = isset($v['other'])?json_encode($v['other']):'';
                        $map[$k]['created_at'] = now();
                        $map[$k]['updated_at'] = now();
                    }
                    DB::table('shop_manage_details')->insert($map);
                }else{
                    return $this->failed('json不是数组',201);
                }

            }
        });
        return $this->success('保存成功');
    }

    protected function getData($request){
        $arr = [];
        if($request->filled('detail')){
            $detail = $request->detail;
            if(is_array($detail)){
                $arr = $detail;
            }else{
                $arr = json_decode($detail,true);
            }

        }
        return $arr;
    }
    public function edit(ShopManager $model,Request $request){
        $model = $model->with('platForm','customer','template','department','detail');
        $data = $model->find($request->id);
        return $this->success($data);
    }
    public function update(ShopManager $model,Request $request){
       $m = $model->find($request->id);
       if(!$m){
           return $this->failed('数据不存在',201);
       }
        $data = $request->only('wx_group','distance_price','plateform_id','template_id','department_id','shop_name','template_name','group_id');
        DB::transaction(function ()use($m,$request,$data) {
            $m->update($data);

            $arr = $this->getData($request);
            foreach ($arr as $k=>$v){
                if(isset($v['id'])&&$v['is_update']==1){

                    $map['key'] = isset($v['key'])?$v['key']:'';
                    $map['value'] = isset($v['value'])?json_encode($v['value']):'';
                    $map['mark'] = isset($v['mark'])?$v['mark']:'';
                    $map['other'] = isset($v['other'])?json_encode($v['other']):'';
                    $map['updated_at'] = now();
                    ShopManageDetail::query()
                        ->where('id',$v['id'])
                        ->where('shop_manage_id',$v['shop_manage_id'])
                        ->update($map);
                    $n['shop_manage_id'] = $v['shop_manage_id'];
                    $n['key'] = $v['key'];
                    $n['value'] = isset($v['value'])?json_encode($v['value']):'';
                    $n['mark'] = isset($v['mark'])?$v['mark']:'';
                    $n['model_id'] = $v['model_id'];
                    $n['created_at'] = now();
                    $n['updated_at'] = now();
                    DB::table('shop_manage_records')->insertGetId($n);
                }
            }

        });
        return $this->success('修改成功');
    }
    public function destory(ShopManager $model,Request $request){
        $data = $model->find($request->id);
        $data->delete();
    }

    /**
     * 导入快捷语录
     */
    public function importShotCut(Request $request){
        $id = $request->shop_manage_id;
        if(!$id){
            return $this->failed('店铺Id不存在',201);
        }
        $res  = Excel::import(new ShortCut($id), $request->file('file'));
        if($res){

            //让快捷语有更新
            $this->setUnreadMessage($request->shop_manage_id);
            $msg='成功导入 ';
            return $this->success(['msg'=>$msg]);
        }
    }


    //下载模板
    public function downLoadShotCut(){
        return response()->download('target/快捷短语模板.xls');
    }
    //设置未读信息
    protected function setUnreadMessage($shop_id){
        $users = $this->getUnreadUser($shop_id);
        if($users){
            $map = [];
            foreach ($users as $k=>$v){
                $map[$k]['shop_manage_id'] = $shop_id;
                $map[$k]['user_id'] = $v;
            }
            DB::table('short_cut_records')->insert($map);
        }

    }
    //终止店铺
    public function finalShop(ShopManager $model,Request $request){
        $model->where('id',$request->id)->update(['cooperation_status'=>2]);
        return $this->success('终止成功');
    }
    //设置已读
    public function isRead(ShopManageRecord $model,Request $request){
        $data = $model->query()->find($request->id);
        if(!$data){
            return $this->failed('数据不存在',201);
        }
        $user = $request->user();

        if(empty($data->unread)){
            $data->unread = $user->id;
            $data->save();
        }else{
            $arr = explode(',',$data->unread);
            if(!in_array($user->id,$arr)){
                $data->unread = $data->unread.','.$user->id;
                $data->save();
            }
        }

        return $this->success('更新成功');
    }
    //操作信息
    public function operatorMessage(ShopManageRecord $model,Request $request){
        $user = $request->user();
        $data = $model->query()->where('shop_manage_id',$request->shop_manage_id)->get();
        foreach ($data as $k=>$v){
            $data[$k]['is_update'] = $this->isUpdate($v->unread,$user->id);
        }
        return $this->success($data);
    }
    //判断用户是否已读
    protected function isUpdate($unRead,$uid){
        if($unRead){
            $arr = explode(',',$unRead);
            if(in_array($uid,$arr)){
                return 1;
            }else{
                return 0;
            }
        }else{
            return 0;
        }
    }
}
